package com.haust.aliyunoos.config;


import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.Date;


@Data
@Component
public class OssUtils {

    @Autowired
    private AliyunOssConfig aliyunOssConfig;

    private OSSClient ossClient;

    @Value("${aliyun.accessKeyId}")
    public String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    public String accessKeySecret;

    @Value("${aliyun.endPoint}")
    public String endpoint;

    @Value("${aliyun.bucketName}")
    public String bucketName;

    public OSSClient initClient() {
        if (null == ossClient) {
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(5000);
            conf.setMaxErrorRetry(10);

            CredentialsProvider provider = new DefaultCredentialProvider("LTAI4G4Hv2pGFNFN7chY2X1L", "kvQbMNsu9eQB23o5m3zFONBRDa18Go");
            ossClient = new OSSClient("oss-cn-beijing.aliyuncs.com", provider, conf);
        }
        return ossClient;
    }

    public String getUrl(String key) {
        initClient();
        // 设置URL过期时间为30s。
        Date expiration = new Date(new Date().getTime() + 30 * 1000);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
       // key="lzh/2021/11/02/655e04ba-3848-4858-8863-4e7b9f85187d.jpg";
        URL url = ossClient.generatePresignedUrl("jinmao-common", key, expiration);
        return url.toString();
    }

}
